<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/9
 * Time: 11:26
 */

namespace Admin\Controller;
use Think\Controller;

class HpageController extends AdminController{
    public function friend(){
        $list =$this->lists(M('Friend'),array(),'sort');
        $this->assign('_list',$list);
        if(isset($_GET['p'])){
            $num = ($_GET['p']-1)*10;
            $this->assign('num', $num);
        }
        $this->meta_title = '友情链接';
        $this->display();
    }

    //友情链接的添加和修改  2016.6.29 teng
    public function friend_menu ()
    {
        if(IS_POST)
        {
            $data    = $_POST;
            if($data['school'] == '')
            {
                $this->error('请输入学校名称');
            }
            if($data['upload_ids'] == '')
            {
                $this->error('请上传图片');
            }
            $data['sort']       = intval($data['sort']);
            $data['img']        = $data['upload_ids'];
            $data['datetime']   = time();
            $model              = M('Friend');
            $data               = $model->create($data);
            if($data['id'])      //修改
            {
                $id     = intval($data['id']);
                $info   = M('Friend')->find($id);
                if(!$info)
                {
                    $this->error('数据不存在');
                }
                else
                {
                    if($model->where('id='.$id)->save($data))
                    {
                        $this->Friend_catch(1);
                        $this->success('修改成功',U('friend'));
                    }
                    else
                    {
                        $this->error('修改失败');
                    }
                }

            }
            else                //添加
            {
                if($model->add($data))
                {
                    $this->Friend_catch(1);
                    $this->success('添加成功',U('friend'));
                }
                else
                {
                    $this->error('添加失败');
                }
            }
        }
        else
        {
            $this->meta_title = '友情链接';
            $this->display();
        }
    }

    //修改  2016.6.29 teng
    public function friend_edit(){
        $id = intval(I('id'));
        if($id)
        {
            $info   = M('Friend')->find($id);
            if($info['id'])
            {
                //显示图片
                $upload_ids_arr = explode(',',$info['img']);
                $this->assign('upload_ids_arr',$upload_ids_arr);
                $this->assign('info',$info);
            }
            else
            {
                JsLocation('数据不存在');
            }
            $this->display('friend_menu');
        }
        else
        {
            JsLocation('数据不存在');
        }
    }

    //删除  2016.6.29 teng
    public function friend_del(){
        $id = intval(I('id'));
        if($id)
        {
            $info   = M('Friend')->find($id);
            if($info)
            {
                if(M('Friend')->delete($id))
                {
                    $this->Friend_catch(1);
                    $this->success('删除成功',U('friend'));
                }
                else
                {
                    $this->error('删除失败');
                }
            }
            else
            {
                $this->error('数据不存在');
            }
        }
        else
        {
            JsLocation('数据不存在');
        }
    }
    public function upload(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $tmp_can	=	$_GET['can']?$_GET['can']:0;
        if($tmp_can==1){
            $upload->exts      =     array('jpg','png','jpeg','gif','bmp');// 设置附件上传类型
        }else{
            $upload->exts      =     array('doc', 'rar','zip','docx');// 设置附件上传类型
        }
        $upload->rootPath  =     './uploads/school/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $tmp_name	=	$_GET['tmp_name'];

        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            echo json_encode(array('state'=>$upload->getError()));
        }else{// 上传成功
            //print_R($info);exit;
            $file=array(
                'uid'=>UID,
                'title'=>$info[$tmp_name]['name'],
                'title_r'=>$info[$tmp_name]['savename'],
                'type'=>'1',
                'size'=>$info[$tmp_name]['size'],
                'dir'=>$upload->rootPath.$info[$tmp_name]['savepath'],
                'create_time'=>date('Y-m-d h:i:s')
            );
            $id = M('Attachment')->add($file);
            echo json_encode(array('state'=>'ok','upload_id'=>$id,'base_file_n'=>$file['title']));
        }
    }

    public function down_file(){
        $file_id=$_GET['file_id'];
        if(empty($file_id)){
            redirect("文件不存在跳转页面");
        }else{//如果要加登录条件，这里可以自己加
            $map['id'] = $file_id;
            $list=D('Attachment')->where($map)->select();
            if ($list == false) {//文件不存在，可以跳转到其它页面
                header('HTTP/1.0 404 Not Found');
                header('Location: .');
            } else {
                $file_name="./".$list[0]['dir'].$list[0]['title_r'];//需要下载的文件
                $file_name=iconv("utf-8","gb2312","$file_name");
                if(file_exists($file_name)){
                    $fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
                    if(!file_exists($file_name)){//判断文件是否存在
                        $this->error('文件不存在！');
                    }
                    $file_size=filesize($file_name);//判断文件大小
                    //返回的文件
                    Header("Content-type: application/octet-stream");
                    //按照字节格式返回
                    Header("Accept-Ranges: bytes");
                    //返回文件大小
                    Header("Accept-Length: ".$file_size);
                    //弹出客户端对话框，对应的文件名
                    Header("Content-Disposition: attachment; filename=".$list[0]['title']);
                    //防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
                    $buffer=1024;
                    while(!feof($fp)){
                        $file_data=fread($fp,$buffer);
                        echo $file_data;
                    }
                    //关闭文件
                    fclose($fp);
                }else{
                    $this->error('文件不存在！');
                }

            }
        }
    }
    private function Friend_catch($tag=''){
        if(empty($tag))		//读取缓存
        {
            return S('Friend_catch');
        }
        else				//写入缓存
        {
            S('Friend_catch',null);
            $order = 'sort asc,datetime desc';
            $model = M('Friend');
//			$list  = $this->lists($model,array(),$order);
            $list  = $model->where('state=1')->order($order)->getField('id,id,url,school,img,datetime,state,sort');
            S('Friend_catch',$list);
            return true;
        }
    }

}